/* eslint-disable react/no-unused-state */
/**
 * Created by XM on 2018/9/3.
 * @email xm@tqzgc.com
 */
import React, { Component } from 'react';
import { Input, Button, Card, Form } from 'antd';
import { FormInstance } from 'antd/lib/form';

/*
const locationIcon = {
  url: 'http://api0.map.bdimg.com/images/copyright_logo.png',
  size: { width: 100, height: 100 },
};
*/
let myValue = null;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 7,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 12,
    },
    md: {
      span: 10,
    },
  },
};
export default class extends Component {
  formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = { address: this.props.value.address ? this.props.value.address : undefined };
    this.setMapRef = (ref) => {
      this.mapContainer = ref;
    };
  }

  componentDidMount() {
    this.createMapScript().then(this.initMap);
  }

  componentWillReceiveProps(nextProps) {
    if (this.inited) return;
    if (!this.mapLoaded) return;
    const { value } = nextProps;
    const { onChange } = this.props;

    let initValue = value;
    if (initValue.point) {
      initValue.point.address = initValue.address;
      onChange(initValue.point);
    }
    const { point: position = { lng: undefined, lat: undefined } } = value;
    const { point: prePosition = { lng: undefined, lat: undefined } } = this.props.value || {};

    if (position.lng && position.lat && !prePosition.lng && !prePosition.lat) {
      const point = new global.BMap.Point(position.lng, position.lat);
      this.map.panTo(point);
      if (this.marker) {
        this.marker.setPosition(point);
      } else {
        this.marker = new global.BMap.Marker(point);
        this.map.addOverlay(this.marker);
      }
      this.inited = true;
    }
  }

  shouldComponentUpdate() {
    return !this.inited;
  }

  componentWillUnmount() {
    if (this.map) {
      this.map.removeEventListener('click', this.onMapClick);
      this.map = null;
    }
    this.props = null;
  }

  clearMark = () => {
    this.map.clearOverlays();
    /* 清除mark */
  };

  onMapClick = (event) => {
    if (!!this.props.value.device) return;
    const { onChange } = this.props;
    const { point } = event;
    // this.setState({ mapCenter: { lng: point.lng, lat: point.lat } });
    // this.clearMark();
    this.map.panTo(new global.BMap.Point(point.lng, point.lat));
    if (this.marker) {
      this.marker.setPosition(point);
    } else {
      this.marker = new global.BMap.Marker(point);
      this.marker.disableMassClear(); /* 不清除点击添加的mark */
      this.map.addOverlay(this.marker);
    }

    const myGeo = new global.BMap.Geocoder();
    myGeo.getLocation(point, (result) => {
      if (onChange) onChange(result);
    });
  };

  onSearch = (value) => {
    if (!this.localSearch) {
      this.localSearch = new global.BMap.LocalSearch(this.map, {
        onSearchComplete: () => {
          const pp = this.localSearch.getResults().getPoi(0).point;
          // this.clearMark();
          this.map.centerAndZoom(pp, 15);
          // this.map.addOverlay(new BMap.Marker(pp));
          pp.address = this.state.address;
          const { onChange } = this.props;
          if (onChange) onChange(pp);
        },
      });
    }
    this.localSearch.search(value);
  };

  onClear = () => {
    if (this.localSearch) {
      this.localSearch.clearResults();
    }
  };

  setCity = (city, zoom) => {
    this.map.setCenter(city);
    if (zoom) this.map.setZoom(zoom);
  };

  setAddress = (payload) => {
    this.setState({
      address: payload,
    });

    this.formRef.current.setFieldsValue({
      address: payload,
    });
  };

  initMap = (BMap) => {
    // this.defaultCenter = getPoint(116.404, 39.915);
    // this.mapContainer = this.mapContainer || this.mapContainerRef.current;
    const that = this;
    const { value } = this.props;
    let ac = null;
    const { point: position } = value || {};
    const map = new BMap.Map(this.mapContainer, { enableMapClick: false });
    if (!this.props.value.device) {
      ac = new BMap.Autocomplete({ input: 'position', location: map });
      ac.addEventListener('onconfirm', function (e) {
        const _value = e.item.value;
        myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
        that.setAddress(myValue);
        that.onSearch(myValue);
      });
    }
    // this.setState({
    //   address:
    // })

    if (Object.keys(map).length === 0) return;
    map.enableScrollWheelZoom();
    const point = new BMap.Point(
      (position && position.lng) || 116.404,
      (position && position.lat) || 39.915,
    );
    map.centerAndZoom(point, 15);
    map.setDefaultCursor('pointer');

    // map.addControl(new BMap.OverviewMapControl({ isOpen: true, size: new BMap.Size(140, 110) }));
    // map.addControl(new BMap.NavigationControl({ type: global.BMAP_NAVIGATION_CONTROL_ZOOM }));
    // map.addControl(new BMap.NavigationControl());

    // map.addEventListener('tilesloaded', ()=>{
    // });
    if (position && position.lng && position.lat) {
      this.marker = new BMap.Marker(point);
      map.addOverlay(this.marker);
    } else {
      const myCity = new BMap.LocalCity();
      myCity.get((result) => {
        map.setCenter(result.name);
      });
    }
    map.addEventListener('click', this.onMapClick);

    this.map = map;
    this.mapLoaded = true;
  };

  createMapScript = () => {
    const ak = 'Ir17SvLFKABa4GpEPjUy3YpZGonvLLn4';

    window.BMap = window.BMap || {};
    if (Object.keys(window.BMap).length === 0) {
      window.BMap.b_preload = new Promise((resolve) => {
        const $script = document.createElement('script');
        document.body.appendChild($script);
        window.b_initBMap = () => {
          resolve(window.BMap);
          document.body.removeChild($script);
          window.BMap.b_preload = null;
          window.b_initBMap = null;
        };

        $script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=b_initBMap`;
      });
      return window.BMap.b_preload;
    }

    if (!window.BMap.b_preload) {
      return Promise.resolve(window.BMap);
    }
    return window.BMap.b_preload;
  };

  render() {
    const {
      width = this.props.size.width,
      height = this.props.size.height,
      marginLeft = this.props.size.marginLeft,
      style,
    } = this.props;
    // const { width = '50%', height = 250, marginLeft = '24%', style } = this.props;
    return (
      <div
        style={{
          marginBottom: 16,
          borderRadius: 5,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'left',
        }}
      >
        {/* <div
          style={{
            display: 'flex',
            alignItems: 'center',
            display: this.props.value.device ? 'none' : '',
          }}
        >
          <Input.Search
            enterButton="搜索"
            // size="small"
            style={{ width: '100%', marginBottom: 8, marginTop: 8 }}
            onSearch={this.onSearch}
            placeholder="输入位置进行搜索"
            // defaultValue={this.props.value.address}
          />
        </div> */}
        {!this.props.value.device ? (
          <div style={{ width: '100%' }}>
            <Form ref={this.formRef}>
              <FormItem
                // {...formItemLayout}
                // label="地点"
                name="position"
                rules={[
                  {
                    required: true,
                    message: '请选择搜索后的地址',
                  },
                ]}
              >
                <Input
                  placeholder={
                    this.props.value.address ? this.props.value.address : '请选择搜索后的地址'
                  }
                  style={{ width: '100%' }}
                />
              </FormItem>
            </Form>
          </div>
        ) : null}
        {this.props.value.device ? (
          <div style={{ textAlign: 'center', marginBottom: 10 }}>
            纬度:{this.props.value.point.lat}，经度:{this.props.value.point.lng}
          </div>
        ) : null}
        <div ref={this.setMapRef} style={{ width, height, marginLeft, ...style }} />
      </div>
    );
  }
}
